package com.sdcqjy.property.home.fragment;

import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.sdcqjy.mylibrary.Logger;
import com.sdcqjy.mylibrary.OtherUtils;
import com.sdcqjy.property.R;
import com.sdcqjy.property.base.BaseFragment;
import com.sdcqjy.property.mode.AttenMode;
import com.sdcqjy.property.mode.ListMsgMode;
import com.sdcqjy.property.utils.TitleUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * webView展示页
 */
public class HtmlFragment extends BaseFragment {
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.textTime)
    TextView textTime;
    @BindView(R.id.textTitle)
    TextView textTitle;
    @BindView(R.id.textAtten)
    TextView textAtten;
    @BindView(R.id.textReadNumb)
    TextView textReadNumb;
    private ListMsgMode mode;
    private AttenMode attenMode;
    private String readNumb;

    public static HtmlFragment newInstance(ListMsgMode mode) {
        Bundle bundle = new Bundle();
        bundle.putParcelable("mode", mode);
        HtmlFragment fragment = new HtmlFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_webview, null);
        ButterKnife.bind(this, view);
        return view;
    }

    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getArguments();
        mode = bundle.getParcelable("mode");

        WebSettings settings = webView.getSettings();

        //缩放开关，设置此属性，仅支持双击缩放，不支持触摸缩放
        //settings.setSupportZoom(true);
        //设置是否可缩放，会出现缩放工具（若为true则上面的设值也默认为true）
        //settings.setBuiltInZoomControls(true);
        //隐藏缩放工具
        settings.setDisplayZoomControls(false);

        // 设置可以支持缩放
        webView.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        webView.getSettings().setBuiltInZoomControls(true);
        //扩大比例的缩放
        webView.getSettings().setUseWideViewPort(true);
        //自适应屏幕
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);


        webView.setBackgroundColor(0xffFFffFF);

        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccess(true); //设置可以访问文件
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.setWebViewClient(new WebViewClient() {
            private boolean loadError;

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Logger.out(url);
                if (url.equals("about:blank") || url.startsWith("mailto:")) {
                } else if (url.startsWith("tel:")) {//电话
                    OtherUtils.callTelOfUri(getActivity(), url);
                } else {
                    webView.loadUrl(url);
                }
                return true;
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                //super.onReceivedError(view, errorCode, description, failingUrl);
                webView.loadUrl("file:///android_asset/err.html");
                loadError = true;
            }
            //            public void onPageFinished(WebView view, String url) {
//                super.onPageFinished(view, url);
//                webView.loadUrl("javascript:" + FullAll);
//                webView.loadUrl("javascript:fullscreen()");
//            }
        });
        webView.setWebChromeClient(new MyWebChromeClient());
        webView.setDownloadListener((url1, userAgent, contentDisposition, mimetype, contentLength) -> {
            Uri uri = Uri.parse(url1);
            Intent intent1 = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent1);
        });
        if (mode != null) {
            webView.loadUrl(mode.htmlPath);
            if (TextUtils.isEmpty(mode.title)) {
                textTitle.setVisibility(View.GONE);
            } else textTitle.setText(mode.title);
            Resources res = getResources();
            String fabushijian_ = res.getString(R.string.fabushijian_);
            if (mode.createTime == 0) {
                textTime.setVisibility(View.GONE);
            } else textTime.setText(fabushijian_ + mode.getTime());
            boolean gone = TitleUtils.isGone(mode.categoryID);

            gone = TitleUtils.has围观and关注(mode.categoryID);
            if (gone) {
                textAtten.setVisibility(View.VISIBLE);
                textReadNumb.setVisibility(View.VISIBLE);
            } else {
                textAtten.setVisibility(View.GONE);
                textReadNumb.setVisibility(View.GONE);
            }
        }
    }

    public void onResume() {
        super.onResume();
        if (handler != null) {
            if (attenMode == null) handler.sendEmptyMessage(1);
            if (readNumb == null) handler.sendEmptyMessage(4);
        }
    }

    public void sendMessage(int type, Object object) {
        if (object == null) return;
        switch (type) {
            case 1:
                if (object instanceof AttenMode) {
                    attenMode = (AttenMode) object;
                    textAtten.setText(attenMode.isAttention == 1 ? R.string.yiguanzhu : R.string._guanzhu);
                }
                break;
            case 4:
                if (object instanceof String) {
                    readNumb = (String) object;
                    String s = getResources().getString(R.string.readHintStr) + readNumb;
                    textReadNumb.setText(s);
                }
                break;
        }
    }

    @OnClick(R.id.textAtten)
    public void onTextAttenClicked() {
        if (isLogin() && handler != null) {
            int isAttention = 0;
            if (attenMode != null) isAttention = attenMode.isAttention;
            handler.sendEmptyMessage(isAttention == 1 ? 3 : 2);
        }
    }

    /**
     * 继承WebChromeClient类
     * 对js弹出框时间进行处理
     */
    public final class MyWebChromeClient extends WebChromeClient {
        /**
         * 处理alert弹出框
         */
        public boolean onJsAlert(WebView view, String url,
                                 String message, JsResult result) {
            new AlertDialog.Builder(getActivity()).
                    setTitle("Alert").setMessage(message).setPositiveButton("OK",
                    (arg0, arg1) -> {
                        //TODO
                    }).create().show();
            result.confirm();
            return true;
        }

        /**
         * 处理confirm弹出框
         */
        public boolean onJsConfirm(WebView view, String url, String message,
                                   JsResult result) {
            result.confirm();
            return super.onJsConfirm(view, url, message, result);
        }

        /**
         * 处理prompt弹出框
         */
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, JsPromptResult result) {
            result.confirm();
            return super.onJsPrompt(view, url, message, message, result);
        }
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            boolean b = webView.canGoBack();
            if (b) {
                webView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
